from app import db
from datetime import datetime
import json

class SyncTask(db.Model):
    """同步任务模型"""
    __tablename__ = 'sync_tasks'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    source_id = db.Column(db.Integer, db.ForeignKey('datasources.id'), nullable=False)
    target_id = db.Column(db.Integer, db.ForeignKey('datasources.id'), nullable=False)
    sync_type = db.Column(db.String(20), nullable=False)  # 全量、增量、定时
    sync_frequency = db.Column(db.String(100))  # cron表达式
    thread_count = db.Column(db.Integer, default=1)  # 同步线程数
    batch_size = db.Column(db.Integer, default=1000)  # 批处理大小
    sync_configs = db.Column(db.Text, nullable=False)  # JSON格式的同步配置列表
    status = db.Column(db.String(20), default='stopped')  # running, stopped, failed
    last_sync_time = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联的同步日志
    sync_logs = db.relationship('SyncLog', backref='task', lazy='dynamic')
    
    def __repr__(self):
        return f'<SyncTask {self.name}>'
    
    def to_dict(self):
        sync_configs = []
        if self.sync_configs:
            try:
                sync_configs = json.loads(self.sync_configs)
            except:
                sync_configs = []
        
        return {
            'id': self.id,
            'name': self.name,
            'source_id': self.source_id,
            'target_id': self.target_id,
            'source_name': self.source_datasource.name if self.source_datasource else None,
            'target_name': self.target_datasource.name if self.target_datasource else None,
            'sync_type': self.sync_type,
            'sync_frequency': self.sync_frequency,
            'thread_count': self.thread_count,
            'batch_size': self.batch_size,
            'sync_configs': sync_configs,
            'status': self.status,
            'last_sync_time': self.last_sync_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_sync_time else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }